const app = getApp()

Page({
  data: {
    activities: [],
    currentActivityIndex: 0,
    teams: [],
    totalMembers: 0,
    averageScore: 0,
    highestScore: 0
  },

  onLoad() {
    this.loadActivities()
  },

  onShow() {
    // 每次显示页面时重新加载数据
    if (this.data.activities.length > 0) {
      this.loadTeams(this.data.activities[this.data.currentActivityIndex]._id)
    }
  },

  onPullDownRefresh() {
    if (this.data.activities.length > 0) {
      this.loadTeams(this.data.activities[this.data.currentActivityIndex]._id, () => {
        wx.stopPullDownRefresh()
      })
    } else {
      this.loadActivities(() => {
        wx.stopPullDownRefresh()
      })
    }
  },

  // 加载活动列表
  loadActivities(callback) {
    wx.cloud.callFunction({
      name: 'getActivities',
      data: {
        role: 'coach'
      }
    }).then(res => {
      const activities = res.result.data
      this.setData({ activities }, () => {
        if (activities.length > 0) {
          this.loadTeams(activities[0]._id)
        }
        callback && callback()
      })
    }).catch(err => {
      console.error('获取活动列表失败：', err)
      wx.showToast({
        title: '获取活动列表失败',
        icon: 'none'
      })
      callback && callback()
    })
  },

  // 加载队伍排名
  loadTeams(activityId, callback) {
    wx.cloud.callFunction({
      name: 'getTeamRanking',
      data: { activityId }
    }).then(res => {
      const teams = res.result.data
      // 计算统计数据
      const totalMembers = teams.reduce((sum, team) => sum + team.memberCount, 0)
      const totalScore = teams.reduce((sum, team) => sum + (team.score || 0), 0)
      const averageScore = teams.length > 0 ? Math.round(totalScore / teams.length) : 0
      const highestScore = teams.length > 0 ? Math.max(...teams.map(team => team.score || 0)) : 0

      this.setData({
        teams,
        totalMembers,
        averageScore,
        highestScore
      })
      callback && callback()
    }).catch(err => {
      console.error('获取队伍排名失败：', err)
      wx.showToast({
        title: '获取队伍排名失败',
        icon: 'none'
      })
      callback && callback()
    })
  },

  // 处理活动选择
  handleActivityChange(e) {
    const index = e.detail.value
    this.setData({
      currentActivityIndex: index
    })
    this.loadTeams(this.data.activities[index]._id)
  }
}) 